package com.zensun.web.controller.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zensun.common.config.AliyunSmsProperties;
import com.zensun.common.constant.Constants;
import com.zensun.common.core.domain.R;
import com.zensun.common.core.redis.RedisCache;
import com.zensun.common.enums.VerifyPhone;
import com.zensun.common.utils.Assert;
import com.zensun.common.utils.sms.AliyunSmsUtil;
import com.zensun.system.domain.SysUser;
import com.zensun.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author gmk
 */
@Api(value = "验证码管理", tags = "验证码管理模块")
@RestController
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    @Autowired
    private ISysUserService userService;

    /**
     * 生成验证码
     */
    @ApiOperation("账户密码登录-----生成验证码")
    @GetMapping("/captchaImage")
    public R getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 2);

        //图形验证码写出，可以写出到文件，也可以写出到流
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        BufferedImage image = lineCaptcha.getImage();

        // 生成验证码
        String code = lineCaptcha.getCode();
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        try {
            ImageIO.write(image, "gif", os);
        } catch (IOException e) {
            return R.error("生成验证码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return R.success(map);
    }

    /**
     * 生成手机验证码
     */
    @ApiOperation("手机号验证码登录-----生成验证码")
    @GetMapping("/captchaTelephone")
    public R getTelephoneCode(@ApiParam("手机号") String phone, @ApiParam("验证类型  （0 登录验证  1 修改手机号验证）") String verify, HttpServletResponse response) throws IOException {
        //TODO 修改手机号的时候不一定是sys_user表
        String template = "";
        if (VerifyPhone.Login.getCode().equals(verify)) {
            LambdaQueryWrapper<SysUser> q = new LambdaQueryWrapper<SysUser>();
            q.eq(SysUser::getTelephone, phone);
            int count = userService.count(q);
            Assert.countLtZero(count, "手机号不存在！");
            //手机登录模板
            template = aliyunSmsProperties.getLoginTemplateCode();
        } else if (VerifyPhone.UPDATE.getCode().equals(verify)) {
            //手机号修改 身份认证模板
            template = aliyunSmsProperties.getUpdatePhoneTemplateCode();
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        Map<String, String> paramMap = new HashMap<String, String>();
        //手机验证码
        String code = AliyunSmsUtil.createRandomVcode();
        paramMap.put("code", code);
        String templateParam = JSONUtil.toJsonStr(paramMap);
        //发送手机验证码
        try {
            AliyunSmsUtil.sendSms(phone, template, templateParam);
        } catch (Exception e) {
            e.printStackTrace();
            R.error("获取验证码失败");
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION_TELEPHONE, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        return R.success(map);
    }
}
